using System;
using System.Runtime.Serialization;
using InfiniTec.Runtime.Serialization;
using Microsoft.Exchange.WebServices.Data;

namespace CalendarSubscriptionApp
{
    /// <summary>
    /// Exception thrown when an Exchange WebServiceCall failed
    /// </summary>
    [Serializable]
    public sealed class ExchangeWebServiceCallFailedException : Exception
    {
        private readonly ServiceResponse _Response;

        public ServiceResponse Response
        {
            get { return _Response; }
        }

        public override void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            base.GetObjectData(info, context);

            info.AddValue("Response", _Response);
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="ExchangeWebServiceCallFailedException"/> class.
        /// </summary>
        /// <param name="response">The response returned from the server.</Param>
        public ExchangeWebServiceCallFailedException(ServiceResponse response)
            : base(GetMessage(response))
        {
            _Response = response;
        }

        private static string GetMessage(ServiceResponse response)
        {
            if (response == null) throw new ArgumentNullException("response");

            return response.ErrorMessage;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="ExchangeWebServiceCallFailedException"/> class.
        /// </summary>
        /// <param name="context">The <see cref="StreamingContext"/> to recreate the exception from.</param>
        /// <param name="info">The <see cref="SerializationInfo"/> to recreate the exception from.</param>
        private ExchangeWebServiceCallFailedException(SerializationInfo info, StreamingContext context) : base(info, context)
        {
            _Response = info.GetValue<ServiceResponse>("Response");
        }
    }
}